package test.niuke;

/**
 * Created by linshuo on 2018/2/25.
 *
 * 反转链表
 */
public class ReverseLinkedList {
    private static class Node {
        int val;
        Node next = null;

        Node(int val) {
            this.val = val;
        }
    }

    private Node reverseList(Node head) {
        Node postNode;
        Node preNode = null;
        Node node = head;
        while (node != null) {
            /* 从最next开始交换起 4行背下来*/
            postNode = node.next;
            node.next = preNode;
            preNode = node;
            node = postNode;
        }
        return preNode;
    }

    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        Node newHead = new ReverseLinkedList().reverseList(node1);
        /* 遍历反转后的链表 */
        while (newHead != null) {
            System.out.println(newHead.val);
            newHead = newHead.next;
        }
    }
}
